package com.zlj.province.city.linkage;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.io.SAXReader;

@WebServlet("/ProvinceServelt")
public class ProvinceServelt extends HttpServlet {
	private static final long serialVersionUID = 1L;

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		/*
		 * 响应所有省份名称，使用逗号分隔！
		 * 1、Document对象
		 *    ** 创建解析器对象
		 *    ** 调用解析器的读方法，传递一个流对象，得到Document
		 */
		response.setContentType("text/html;charset=utf-8");  
		try {
			//得到Document
			SAXReader reader = new SAXReader();  
			InputStream io = this.getClass().getResourceAsStream("/china.xml");
			Document doc = reader.read(io);
			/*
			 * 查询所有province的name属性，得到一堆的属性对象
			 * 循环遍历，把所有的属性值连接成一个字符串，发送给客户端
			 */
			StringBuilder sb = new StringBuilder();
			List<Attribute> nodes = doc.selectNodes("//province/@name");  ////province/@name 表示没有深度限制的查找province元素的name属性
			for (int i = 0; i < nodes.size(); i++) {
				sb.append(nodes.get(i).getValue());   //把每个属性的值存放到sb中
				if(i < nodes.size() -1) {
					sb.append(",");
				}
			}
			response.getWriter().print(sb);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
